package cl.gob.minvu.catastromobile.dao;

import cl.gob.minvu.catastromobile.entities.Usuario;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

/**
 * @author psep
 * 
 */
public class UsuarioDAO {
	
	private DatabaseHelper dataHelper;
	private SQLiteDatabase db;

	public static String[] FIELDS_USER = { "run", "dv", "email", "token",
			"profesion", "passwd", "region", "comuna", "nombres",
			"apellidoPaterno", "apellidoMaterno" };
	public static String TABLE_USER = "Usuario";

	/**
	 * @param context
	 */
	public UsuarioDAO(Context context) {
		this.dataHelper = new DatabaseHelper(context);
	}
	
	public void open() {
		this.db = this.dataHelper.getWritableDatabase();
	}
	
	public void close() {
		this.db.close();
	}
	
	@Override
	public void finalize() {
		this.dataHelper.close();
	}

	/**
	 * @param user
	 * @return
	 */
	public boolean insert(Usuario user) {
		boolean result = false;
		this.open();

		try {			
			ContentValues content = new ContentValues();
			content.put(FIELDS_USER[0], user.run);
			content.put(FIELDS_USER[1], String.valueOf(user.dv));
			content.put(FIELDS_USER[2], user.email);
			content.put(FIELDS_USER[3], user.token);
			content.put(FIELDS_USER[4], user.profesion);
			content.put(FIELDS_USER[5], user.passwd);
			content.put(FIELDS_USER[6], user.region);
			content.put(FIELDS_USER[7], user.comuna);
			content.put(FIELDS_USER[8], user.nombres);
			content.put(FIELDS_USER[9], user.apellidoPaterno);
			content.put(FIELDS_USER[10], user.apellidoMaterno);

			this.db.insert(TABLE_USER, null, content);

			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			this.close();
		}

		return result;
	}

	/**
	 * @param user
	 * @return
	 */
	public Usuario retrieve() {
		Usuario usuario = null;
		this.open();

		Cursor c = this.db.query(TABLE_USER, FIELDS_USER,
				null, null, null, null, null);

		if (c.moveToNext()) {
			usuario = new Usuario();
			usuario.run = c.getInt(0);
			usuario.dv = c.getString(1).toCharArray()[0];
			usuario.email = c.getString(2);
			usuario.token = c.getString(3);
			usuario.profesion = c.getString(4);
			usuario.passwd = c.getString(5);
			usuario.region = c.getInt(6);
			usuario.comuna = c.getInt(7);
			usuario.nombres = c.getString(8);
			usuario.apellidoPaterno = c.getString(9);
			usuario.apellidoMaterno = c.getString(10);
		}
		
		c.close();
		this.close();
		
		return usuario;
	}

}
